package com.home.qh.webapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.City;
import com.home.qh.model.Store;
import com.home.qh.service.CityManager;
import com.home.qh.service.StoreManager;

@Controller
public class StoreController {
	private transient final Log log = LogFactory.getLog(StoreController.class);
	private StoreManager storeManager;
	private CityManager cityManager;
	
    @Autowired
    private ApplicationContext context;
    
    @Autowired
    public void setStoreManager(StoreManager storeManager) {
        this.storeManager = storeManager;
    }
    
    @Autowired
	public void setCityManager(CityManager cityManager) {
		this.cityManager = cityManager;
	}
	
    @RequestMapping(value = "/admin/storeList.*", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView listCities(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'handleRequest' method...");
        }
        
        Store storeSearch = new Store();
        String paramValue = request.getParameter("name");
        String paramCityValue = request.getParameter("city");
        if (paramValue != null && !"".equalsIgnoreCase(paramValue.trim()) && !"null".equalsIgnoreCase(paramValue))
        {
        	storeSearch.setCode(paramValue);
        	storeSearch.setName(paramValue);
        }
        
        if (paramCityValue != null
				&& !"".equalsIgnoreCase(paramCityValue.trim())
				&& !"null".equalsIgnoreCase(paramCityValue)) {
			Long paramCityId = null;
			try {
				paramCityId = Long.parseLong(paramCityValue);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (paramCityId != null) {
				City citySearch = new City();
				citySearch.setId(paramCityId);
				storeSearch.setCity(citySearch);
			}

		}
        ModelAndView view = new ModelAndView("admin/storeList");
        view.addObject("cityList", cityManager.getAll());
        view.addObject("storeSearch", storeSearch);
        
        view.addObject("storeList", storeManager.getStoreByStore(storeSearch, null, false, -1, -1));
        return view;

    }

}
